
import { login } from '@/api/user'
import { Message } from 'element-ui'
import router from '@/router'
const moment = require('moment')
export default {
  namespaced: true,
  state () {
    return {
      token: null,
      userName: localStorage.getItem('user'),
      time1: moment().startOf('month').format('YYYY-MM-DD'),
      time2: moment().subtract(0, 'days').format('YYYY-MM-DD')
    }
  },
  mutations: {
    setUserToken (state, token) {
      state.token = token
    },
    setUserName (state, userName) {
      state.userName = userName
      localStorage.setItem('user', userName)
    }
  },
  actions: {
    async Login (context, payload) {
      const res = await login(payload)
      console.log(res)
      context.commit('setUserToken', res.token)
      context.commit('setUserName', res.userName)

      const { msg, success, token, userName } = res
      if (success) {
        return { token, userName }
      } else {
        Message.error(msg)
        return Promise.reject(new Error(msg))
      }
    },

    logout (context) {
      context.commit('setUserToken')
      router.push('/login')
      localStorage.removeItem('user')
    }
  }
}
